package com.cmii.sjw.department.control.jsc.service.impl;

import com.cmii.sjw.department.control.common.AccessTokenFetcher;
import com.cmii.sjw.department.control.jsc.model.*;
import com.cmii.sjw.department.control.jsc.model.base.InstitutionsData;
import com.cmii.sjw.department.control.jsc.model.base.OrderStatData;
import com.cmii.sjw.department.control.jsc.model.base.StudentStatData;
import com.cmii.sjw.department.control.jsc.service.SupervisionService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;


@Slf4j
@Service
public class SupervisionServiceImpl implements SupervisionService {

    @Autowired
    private RestTemplate restTemplate;

    private final ObjectMapper objectMapper = new ObjectMapper();


    // 接口URL列表
    private final String[] apiUrls = {
            //学生统计
            "http://23.210.23.13:9000/edu-data-management/api/v1/broker/api/37",
            //订单统计
            "http://23.210.23.13:9000/edu-data-management/api/v1/broker/api/38",
            //机构统计
            "http://23.210.23.13:9000/edu-data-management/api/v1/broker/api/39",
    };

    /**
     * 学生统计
     *
     * @return 获取json数据
     */
    @Override
    public StudentStatData statistics() {
        try {
            String accessToken = new AccessTokenFetcher().fetchAccessToken();
            log.info("使用的访问令牌: {}", accessToken);

            HttpHeaders headers = new HttpHeaders();
            headers.set("X-Auth-Token", accessToken);
            headers.setContentType(MediaType.APPLICATION_JSON);

            int page = 1;
            int pageSize = 100;
            String url = apiUrls[0] + "?page=" + page + "&pageSize=" + pageSize;

            HttpEntity<?> entity = new HttpEntity<>(headers);

            ResponseEntity<String> response = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    String.class
            );

            if (!response.getStatusCode().is2xxSuccessful()) {
                log.error("HTTP 请求失败: {} 状态码: {}", url, response.getStatusCodeValue());
                throw new RuntimeException("学生统计接口请求失败");
            }

            String responseBody = response.getBody();
            JsonNode rootNode = objectMapper.readTree(responseBody);

            int totalCount = rootNode.path("totalCount").asInt(0);
            JsonNode resultsNode = rootNode.path("results");

            List<StudentStat> studentStats = new ArrayList<>();

            if (resultsNode.isArray()) {
                for (JsonNode resultNode : resultsNode) {
                    StudentStat stat = new StudentStat()
                            .setId(resultNode.path("id").asText())
                            .setAreaCode(resultNode.path("area_code").asText().trim())
                            .setAreaName(resultNode.path("area_name").asText().trim())
                            .setStudentNum(resultNode.path("student_num").asText());

                    studentStats.add(stat);
                }
            } else {
                log.error("响应中未找到有效的 results 字段: {}", responseBody);
                throw new RuntimeException("响应中未找到有效的结果");
            }

            return new StudentStatData()
                    .setTotalCount(totalCount)
                    .setResults(studentStats);

        } catch (Exception e) {
            log.error("调用学生统计接口失败 {}: {}", apiUrls[0], e.getMessage(), e);
            throw new RuntimeException("学生统计数据处理失败", e);
        }
    }

    @Override
    public OrderStatData order() {
        try {
            String accessToken = new AccessTokenFetcher().fetchAccessToken();
            log.info("使用的访问令牌: {}", accessToken);

            HttpHeaders headers = new HttpHeaders();
            headers.set("X-Auth-Token", accessToken);
            headers.setContentType(MediaType.APPLICATION_JSON);

            int page = 1;
            int pageSize = 100;
            String url = apiUrls[1] + "?page=" + page + "&pageSize=" + pageSize;

            HttpEntity<?> entity = new HttpEntity<>(headers);

            ResponseEntity<String> response = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    String.class
            );

            if (!response.getStatusCode().is2xxSuccessful()) {
                log.error("订单统计接口请求失败: {} 状态码: {}", url, response.getStatusCodeValue());
                throw new RuntimeException("订单统计接口请求失败");
            }

            String responseBody = response.getBody();
            JsonNode rootNode = objectMapper.readTree(responseBody);

            int totalCount = rootNode.path("totalCount").asInt(0);
            JsonNode resultsNode = rootNode.path("results");

            List<OrderStat> orderStats = new ArrayList<>();

            if (resultsNode.isArray()) {
                for (JsonNode resultNode : resultsNode) {
                    OrderStat stat = new OrderStat()
                            .setId(resultNode.path("id").asText())
                            .setAreaCode(resultNode.path("area_code").asText().trim())
                            .setAreaName(resultNode.path("area_name").asText().trim())
                            .setOrderNum(resultNode.path("order_num").asText());

                    orderStats.add(stat);
                }
            } else {
                log.error("订单统计响应中未找到有效 results 字段: {}", responseBody);
                throw new RuntimeException("订单统计响应格式不正确");
            }

            return new OrderStatData()
                    .setTotalCount(totalCount)
                    .setResults(orderStats);

        } catch (Exception e) {
            log.error("调用订单统计接口失败 {}: {}", apiUrls[1], e.getMessage(), e);
            throw new RuntimeException("订单统计数据处理失败", e);
        }
    }

    @Override
    public InstitutionsData institutions() {
        try {
            String accessToken = new AccessTokenFetcher().fetchAccessToken();
            log.info("使用的访问令牌: {}", accessToken);

            HttpHeaders headers = new HttpHeaders();
            headers.set("X-Auth-Token", accessToken);
            headers.setContentType(MediaType.APPLICATION_JSON);

            int page = 1;
            int pageSize = 100;
            String url = apiUrls[2] + "?page=" + page + "&pageSize=" + pageSize;

            HttpEntity<?> entity = new HttpEntity<>(headers);

            ResponseEntity<String> response = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    String.class
            );

            if (!response.getStatusCode().is2xxSuccessful()) {
                log.error("教育机构统计接口请求失败: {} 状态码: {}", url, response.getStatusCodeValue());
                throw new RuntimeException("教育机构统计接口请求失败");
            }

            String responseBody = response.getBody();
            JsonNode rootNode = objectMapper.readTree(responseBody);

            int totalCount = rootNode.path("totalCount").asInt(0);
            JsonNode resultsNode = rootNode.path("results");

            List<Institutions> list = new ArrayList<>();

            if (resultsNode.isArray()) {
                for (JsonNode resultNode : resultsNode) {
                    Institutions item = new Institutions()
                            .setId(resultNode.path("id").asText())
                            .setAreaCode(resultNode.path("area_code").asText().trim())
                            .setAreaName(resultNode.path("area_name").asText().trim())
                            .setInstitutionNum(resultNode.path("institution_num").asText());

                    list.add(item);
                }
            } else {
                log.error("教育机构统计响应中未找到有效 results 字段: {}", responseBody);
                throw new RuntimeException("教育机构统计响应格式不正确");
            }

            return new InstitutionsData()
                    .setTotalCount(totalCount)
                    .setResults(list);

        } catch (Exception e) {
            log.error("调用教育机构统计接口失败 {}: {}", apiUrls[2], e.getMessage(), e);
            throw new RuntimeException("教育机构统计数据处理失败", e);
        }
    }
}